package com.lwl.blog.web.controller;

import com.lwl.blog.core.exception.JsonException;
import com.lwl.blog.core.utils.R;
import com.lwl.blog.web.entity.UserEntity;
import com.lwl.blog.web.service.impl.LikeService;
import com.lwl.blog.web.vo.LikeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * <p>
 * 点赞方法
 * </p>
 *
 * @author lwl
 * @since 22-12-28
 */

@RestController
@RequestMapping("/like")
public class LikeController {

    //注入serivcce层
    @Autowired
    private LikeService likeService;

    //点赞方法
    @PostMapping("/clickLike")
    public R clickLike(@RequestBody LikeVo likeVo, HttpSession session) {

        //1.判断用户是否登陆，从session中拿id
        UserEntity userEntity = (UserEntity) session.getAttribute("loginUser");
        if (userEntity == null) {
            //没有登陆抛出一个异常
            throw new JsonException(301, "请先登录!");
        }

        //获得是谁点的赞
        likeVo.setUserId(userEntity.getId());

        //2.调用业务层实现点赞功能,携带点赞人的id,返回是否点赞
        likeService.clickLike(likeVo);

        //3.查询登录用户是否点赞
        Boolean isLike = likeService.isLike(likeVo);

        //4.查询最新的点赞数量
        Long LikeCount = likeService.getInvitataionLikeCount(likeVo.getEntityId());

        //5.返回r层
        R ok = R.ok();
        ok.put("likeStatus", isLike ? 1 : 0);
        ok.put("likeCount",LikeCount);
        return ok;
    }


}
